import {Component, OnInit} from "@angular/core";
import {CommService} from "./comm-service";
import {FileItem, FileLikeObject, FileUploader, ParsedResponseHeaders} from "ng2-file-upload";

declare var $: any;

@Component({
  template: `
    <div class="notfind">
      <div>找不到该页面</div>
    </div>
    <form class="form-horizontal" role="form">
      <div class="row">
        <div class="col-lg-10">
          <input class="form-control" type="file" ng2FileSelect [uploader]="uploader"
                 (change)="selectedFileOnChanged($event)" multiple id="ngselectFileInput"/>
          <div class="input-group" (click)="selectFile()">
            <div class="input-icon">
              <!--<input class="form-control" type="text" name="filename" readonly-->
              <!--[value]="filename">-->
            </div>
            <span class="input-group-btn"><button class="btn btn-success" type="button"><i
              class="fa fa-file"></i> 选择</button></span>
          </div>
        </div>
        <div class="col-lg-2">
          <button type="button" class="btn blue" (click)="dr()">导入</button>
        </div>
      </div>
    </form>

    <div *ngIf="uploadFileList.length">
      <div class="item" *ngFor="let item of uploadFileList;index as index">{{item.filename}}
        <div class="removeK" (click)="removeFromQueue(item.file,index)"><i class="fa fa-close"></i></div>

      </div>
    </div>

    <!--<div id="show"></div>-->
    <!--<div class="area" id="area">-->

    <!--</div>-->

    <!--<button (click)="addEvent()">给上面红色区域绑定点击事件</button>-->
    <!--<button (click)="removeEvent()">解绑点击事件</button>-->

  `,
  styles: [
    '.notfind{height: 50px;width:100px;color: red;margin: 300px auto}',
    "#ngselectFileInput{display: none}",
    ".area{width: 300px;height: 300px;background-color: red}",
    ".item{width: 100px;height: 50px;padding: 10px;text-align: center;color: #ffffff;position: relative;float: left;margin-right: 10px;border: 1px solid red}",
    ".item>.removeK{position: absolute;right: 5px;top: 5px;cursor: pointer;width: 10px;height: 10px;font-size: 20px;text-align: center}",
  ]
})
export class NotfindCompontent implements OnInit {
  // filename: string;
  uploader: FileUploader;

  uploadFileList: any[] = [];
  // handerdom: any;
  // handevent: any;
  //
  // addEvent(): void {
  //   this.handerdom.attachEvent("onclick", this.handevent);
  // }
  //
  // removeEvent(): void {
  //   document.getElementById("show").innerText = "";
  //   this.handerdom.detachEvent("onclick", this.handevent);
  // }
  //
  // show(): void {
  //   document.getElementById("show").innerText = "点击红色区域触发";
  //   console.log(this.text);
  // }

  initUploader(): void {
    this.uploader = new FileUploader({
      url: `${this.commservice.uploadFileurl}manager/attachment/uploadAttachment`,
      method: "POST",
      itemAlias: "files",
      autoUpload: false,//选择文件后，不自动上传
    });
    this.uploader.setOptions({
      headers: [{name: "User-Token", value: this.commservice.getToken()}],
      allowedFileType: ["image"],
    });
  }

  initUploaderEvent() {
    this.uploader.onAfterAddingFile = this.afterAddFile.bind(this);
    this.uploader.onWhenAddingFileFailed = this.whenAddFileFailed.bind(this);
    this.uploader.onBuildItemForm = this.buildItemForm.bind(this);
    this.uploader.onProgressItem = this.onProgress.bind(this);
    this.uploader.onSuccessItem = this.successItem.bind(this);
  }

  buildItemForm(file: FileItem, form: any): void {
    form.append("name", "");
  }

  selectFile(): void {
    $("#ngselectFileInput").click();
  }


  selectedFileOnChanged(e: any): void {
    console.log(e);
  }


  afterAddFile(file: FileItem): void {
    // this.filename = file.file.name;
    // this.nowfile = file;
    const filename = file.file.name;
    this.uploadFileList.push({
      filename: filename,
      file: file
    });
  }

  removeFromQueue(file: FileItem, index: number): void {
    this.uploader.removeFromQueue(file);
    this.uploadFileList.splice(index, 1);
  }

  dr(): void {
    //this.uploader.uploadItem(this.nowfile);
    this.uploader.uploadAll();
  }

  whenAddFileFailed(item: FileLikeObject, filter: any, options: any): void {
    debugger
  }

  /**
   * 上传进度
   * @param {FileItem} fileItem  上传的文件
   * @param progress     该文件的上传进度
   * @returns {any}
   */
  onProgress(fileItem: FileItem, progress: any): any {
    console.log("文件上传进度", progress);
  }

  successItem(item: FileItem, response: string, status: number, headers: ParsedResponseHeaders): void {
    if (status == 200) {
      const respbody = JSON.parse(response);
      const ywcode = respbody.code; // 业务接口code 【8001(signkey 失效)】,【 200】【其他的失败直接抛出 message】
      const ywmsg = respbody.message; // 业务接口提示信息
      const ywresult = respbody.result;// 业务接口返回的数据
      if (ywcode === 8001) {
        // 【signkey 失效】， 重新获取signkey 并且 重新请求
        // 改写返回中的code值
        respbody.code = 202;
      }
      this.commservice.handResponse("get", "manager/attachment/uploadAttachment", respbody, (arg1, resp, arg2) => {
        if (arg1) {
          const retobj = {
            fileId: "",
            filepath: "",
            flag: "",
            msg: '',
          };
          if (arg2) {
            const filearr = resp;
            if (filearr && filearr.length) {
              const fileobj = filearr[0];
              const fileId = fileobj.id;
              const filepath = fileobj.thumbPath;
              const filename = fileobj.originalName;
              retobj['fileId'] = fileId;
              retobj["filepath"] = filepath;
              retobj['flag'] = "success";
              retobj["msg"] = "上传成功";

            }
          } else {
            retobj['flag'] = "fail";
            retobj["msg"] = "上传失败";
          }
          // 如果有返回的还需要根据返回处理
          // this.outMethod.emit(retobj);
        } else {
          this.commservice.warn("上传文件", '签名失败', "manager/attachment/uploadAttachment");
        }
      });
    } else {
      // 上传文件后获取服务器返回的数据错误
    }
  }

  constructor(private commservice: CommService) {

  }

  ngOnInit() {
    this.initUploader();
    this.initUploaderEvent();
    // this.handerdom = document.getElementById("area");
    // this.handevent = this.show.bind(this);
  }
}

